package com.propertyportal.propertylistfragment;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnActionExpandListener;
import com.dropbox.client2.DropboxAPI;
import com.dropbox.client2.android.AndroidAuthSession;
import com.dropbox.client2.session.AccessTokenPair;
import com.dropbox.client2.session.AppKeyPair;
import com.dropbox.client2.session.Session.AccessType;
import com.personhelper.PersonHelper;
import com.propertyportal.alladapter.PropertyListAdapter;
import com.propertyportal.manageproperty.*;
import com.propertyportal.propertylist.LocationHelper;


public class PropertyList extends SherlockFragment {

	public static List<PropertyHelper> property = new ArrayList<PropertyHelper>();
	public static List<PersonHelper> person = new ArrayList<PersonHelper>();
	public static List<Integer> tracknumberofperson=new ArrayList<Integer>();
	public static SherlockFragmentActivity fa;
	//private Context context;
	public static ListView list;
	public String isShowing = null;
	public static PropertyListAdapter adapter;
	public OnClickSelectedListener mCallback;
	public static final String KEY_ID = "propertyId";
	public static final String KEY_NAME = "propertyName";
	public static final String KEY_DESCRIPTION = "propertyDescription";
	public static final String KEY_PRICE = "price";;
	public static final String KEY_TYPE = "propertyType";
	public static final String KEY_STATUS = "status";
	public static final String KEY_SELLING = "sellingType";
	//location key
	public static final String KEY_LATITUDE = "latitude";
	public static final String KEY_LONGITUDE = "longitude";
	public static final String KEY_ADDRESS = "address";
	public static final String KEY_LOCATION = "locationCollection";
	
	//person key
	public static final String KEY_FNAME="firstName";
	public static final String KEY_LNAME="lastName";
	public static final String KEY_LANDLINE="landline";
	public static final String KEY_EMAIL="emailAddress";
	public static final String KEY_MOBILE="mobile";
	
	public PropertyHelper ph;
	public PersonHelper persons;
	public LocationHelper loc;
	public Integer count=0;
	
	//dropbox
	final static private String APP_KEY = "mcret8mq7n203re";
    final static private String APP_SECRET = "o9avsnzk98ajwxh";
    final static private AccessType ACCESS_TYPE = AccessType.APP_FOLDER;
   
    final static private String ACCOUNT_PREFS_NAME = "prefs";
    final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
    final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";

    public static DropboxAPI<AndroidAuthSession> mDBApi;
    //private SharedPreferences session;

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		
		 try {
	            mCallback = (OnClickSelectedListener) activity;
	        } catch (ClassCastException e) {
	            throw new ClassCastException(activity.toString()
	                    + " must implement OnHeadlineSelectedListener");
	        }
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.propertylist, container, false);
		fa = (SherlockFragmentActivity) super.getActivity();
		//context = getActivity().getApplicationContext();
		list = (ListView) view.findViewById(R.id.listView1);
		property.clear();
		person.clear();
		tracknumberofperson.clear();
		adapter = new PropertyListAdapter(getActivity(),property);
		
		AndroidAuthSession session = buildSession();
        mDBApi = new DropboxAPI<AndroidAuthSession>(session);
		
		new LoadData().execute();
		//Toast.makeText(getActivity(), persons.toString(), Toast.LENGTH_LONG).show();
		setHasOptionsMenu(true);
		return view;
	}
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		if (mDBApi.getSession().authenticationSuccessful()) {
			AccessTokenPair tokens;
			try {
				// Required to complete auth, sets the access token on the
				// session
				mDBApi.getSession().finishAuthentication();

				tokens = mDBApi.getSession().getAccessTokenPair();
				storeKeys(tokens.key, tokens.secret);
				System.out.println(tokens);
			} catch (IllegalStateException e) {
				Log.i("DbAuthLog", "Error authenticating", e);
			}
		}
	}
	public void callUpdate(){
		property.clear();
		new LoadData().execute();
	}
	public void display() {

		String result = this.getAllProperty();

		if (result != null) {
			try {

				JSONArray array = new JSONArray(result);
		
				for (int i = 0; i < array.length(); i++) {
					JSONObject e = array.getJSONObject(i);
					
					
					
		
					JSONArray lo = e.getJSONArray(KEY_LOCATION);
					
					for(int j=0;j<lo.length();j++){
						
						JSONObject l=lo.getJSONObject(j);
					
						ph = new PropertyHelper(e.getString(KEY_NAME),
								e.getString(KEY_PRICE), e.getInt(KEY_ID),
								e.getInt(KEY_STATUS), e.getInt(KEY_TYPE),
								e.getInt(KEY_SELLING),
								e.getString(KEY_DESCRIPTION),l.getString(KEY_ADDRESS),l.getString(KEY_LONGITUDE),l.getString(KEY_LATITUDE));
					}
					
					JSONArray per = e.getJSONArray("personCollection");
					int k;
					
					for(k=0;k<per.length();k++){
						
						int counter;
						JSONObject pers=per.getJSONObject(k);
						
						JSONArray con = pers.getJSONArray("contactsCollection");
						
						for(counter=0;counter<con.length();counter++){
							JSONObject	conz=con.getJSONObject(counter);
							persons = new PersonHelper(pers.getString(KEY_FNAME),
									pers.getString(KEY_LNAME),conz.getString(KEY_EMAIL),
									conz.getString(KEY_LANDLINE),
									conz.getString(KEY_MOBILE));	
						}
						person.add(persons);
						
					}
					tracknumberofperson.add(k);
					property.add(ph);
					
				}
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString()
						+ "diri jud");
			} finally {

			}
			

		} else {
			// Toast.makeText(getActivity(), "No data",
			// Toast.LENGTH_LONG).show();
		}
		/*System.out.println(tracknumberofperson.toString());
  		System.out.println("track:"+tracknumberofperson.size());
		System.out.println("person siez:"+person.size());
		System.out.println("p_size:"+property.size());*/
	}

	public String getAllProperty(){
		String urls = "http://192.168.2.38:8080/STTHERESEREALTYWS/webresources/com.propertyportal.entities.property/getAllProperty";

	    String json = "";
		try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(urls);
 
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
           // is = httpEntity.getContent();          
            json = EntityUtils.toString(httpEntity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
              
        return json;
	    }  
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);
		menu.clear();
		inflater.inflate(R.menu.manage_property, menu);

		final View v = (View) menu.findItem(R.id.menu_search).getActionView();
		final EditText txtSearch = (EditText) v.findViewById(R.id.search);

		txtSearch.addTextChangedListener(textWatcher);

		// Capture Text in EditText
		txtSearch.addTextChangedListener(textWatcher);

		// Show the search menu item in menu.xml
		MenuItem menuSearch = menu.findItem(R.id.menu_search);

		menuSearch.setOnActionExpandListener(new OnActionExpandListener() {

			// Menu Action Collapse
			@Override
			public boolean onMenuItemActionCollapse(MenuItem item) {
				// Empty EditText to remove text filtering
				txtSearch.setText("");
				txtSearch.clearFocus();
				return true;
			}

			// Menu Action Expand
			@Override
			public boolean onMenuItemActionExpand(MenuItem item) {
				// Focus on EditText
				txtSearch.requestFocus();

				// Force the keyboard to show on EditText focus
				InputMethodManager imm = (InputMethodManager) getActivity()
						.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
				return true;
			}
		});

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.refresh:
			property.clear();
			new LoadData().execute();
			return true;
		case R.id.create:
			PropertyDetail pd=(PropertyDetail)getFragmentManager().findFragmentById(R.id.article_fragment);
			
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
			
			AddProperty addproperty=new AddProperty();
			
			if(pd!=null){
			transaction.replace(R.id.article_fragment, addproperty);		
			}
			else{	
			transaction.replace(R.id.fragment1, addproperty);	
			}
			transaction.addToBackStack(null);
			transaction.commit();
			
			return true;
			
		default:

			return super.onOptionsItemSelected(item);
		}

	}

	private TextWatcher textWatcher = new TextWatcher() {
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (!property.isEmpty()) {
				adapter.filter(s.toString());
			}
			if (s.toString().equals("")) {
				list.setAdapter(adapter);
			}
		}
		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}
	};

	public class LoadData extends AsyncTask<Void, Void, Void> {

		private ProgressDialog dialog = new ProgressDialog(fa);

		protected void onPreExecute() {

			dialog.setMessage("Loading...");
			dialog.show();
		}

		@Override
		protected Void doInBackground(final Void... unused) {

			try {
				property.clear();
				person.clear();
				tracknumberofperson.clear();
				display();

			} catch (Exception e) {
				Log.e("", "wala jud ma add", e);
			}
			return null;
		}

		protected void onPostExecute(Void result) {
			list.setAdapter(adapter);
			if (this.dialog != null) {
				this.dialog.dismiss();
			}
			//Toast.makeText(getActivity(), property.toString(), Toast.LENGTH_LONG).show();
		}

	}

	public interface OnClickSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(View v, int position);
		public void onEditSelected(View v, int position);
		public void onClickDelete(View v, int position);
		public void onInsertImage(View v, int position);
	}
	private String[] getKeys() {
	     SharedPreferences prefs = getActivity().getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
	     String key = prefs.getString(ACCESS_KEY_NAME, null);
	     String secret = prefs.getString(ACCESS_SECRET_NAME, null);
	     if (key != null && secret != null) {
	            String[] ret = new String[2];
	            ret[0] = key;
	            ret[1] = secret;
	            return ret;
	     } else {
	            return null;
	     }
	}
	     private void storeKeys(String key, String secret) {
	     // Save the access key for later
	     SharedPreferences prefs = getActivity().getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
	     Editor edit = prefs.edit();
	     edit.putString(ACCESS_KEY_NAME, key);
	     edit.putString(ACCESS_SECRET_NAME, secret);
	     edit.commit();
	}
	    private AndroidAuthSession buildSession() {
	    AppKeyPair appKeyPair = new AppKeyPair(APP_KEY, APP_SECRET);
	    AndroidAuthSession session;

	    String[] stored = getKeys();
	    if (stored != null) {
	           AccessTokenPair accessToken = new AccessTokenPair(stored[0], stored[1]);
	           session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE, accessToken);
	    } else {
	           session = new AndroidAuthSession(appKeyPair, ACCESS_TYPE);
	    }

	    return session;
	}  

}
